package gini2p

import (
	"os"

	"time"

	"fmt"

	"strings"

	"github.com/labstack/gommon/log"
)

var ignorefiles = []string{
	".#",
}

func Init() {
	if false {
		done := make(chan bool)
		pwd, _ := os.Getwd()
		checkdir(pwd)

		ticker := time.NewTicker(time.Second * 3)
		list := make(map[string]time.Time)
		for {
			_ = <-ticker.C
			newlistchan := make(chan map[string]time.Time)
			go func() {
				newlistchan <- checkdir(pwd)
			}()
			newlist := <-newlistchan
			if len(list) != 0 && !checkFiles(list, newlist) {
				fmt.Println("reboot")
				os.Exit(1)
			}
			list = newlist
		}
		<-done
	}
}

//比较两个map是否相同
func checkFiles(one map[string]time.Time, two map[string]time.Time) bool {
	if len(one) != len(two) {
		return false
	}
	for k := range one {
		if _, ok := one[k]; !ok {
			return false
		}
		if one[k].UnixNano() != two[k].UnixNano() {
			return false
		}
	}
	return true
}

func checkerr(err error, str string) {
	if err != nil {
		log.Fatal(err, str)
		os.Exit(1)
	}
}

func checkdir(dir string) map[string]time.Time {
	pwdfile, err := os.Open(dir)
	checkerr(err, "打开文件出错")

	filelist, err := pwdfile.Readdir(-1)
	checkerr(err, "读取目录失败")
	list := make(map[string]time.Time)
	for _, v := range filelist {
		if !v.IsDir() {
			if checkFileOrigin(v.Name()) {
				continue
			}
			list[dir+string(os.PathSeparator)+v.Name()] = v.ModTime()
		} else {
			checkdir(dir + string(os.PathSeparator) + v.Name())
		}
	}
	return list
}

func checkFileOrigin(origin string) bool {
	for _, v := range ignorefiles {
		if strings.HasPrefix(origin, v) {
			return true
		}
	}
	return false
}
